package com.zf.netty.file;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.net.InetAddress;
import java.net.ServerSocket;

import org.apache.log4j.Logger;

public class Main {
	private static final Logger LOGGER = Logger.getLogger(Main.class);
	private static FileServer fileServer;
	public static String appUrl = "http://git.oschina.net/zhangfeng0103/fast-scanqrcode-download";
	public static String appTitle = "快捷扫码下载by张峰";
	public static String appStartDesc = "点击查看源码&Star";
	public static String fileName = "";
	public static void main(final String[] args) {
		// 参数
		if (args.length < 1 || args[0] == null || args[0].equals("")) {
			LOGGER.warn("参数错误");
			System.exit(1);
		}
		fileName = args[0];

		try {
			// 简单点，读取空闲的可用端口
			ServerSocket serverSocket = new ServerSocket(0);
			final int port = serverSocket.getLocalPort();
			serverSocket.close();
			
			// 打开一个可视化窗口用来展示二维码
			new SwingPane(String.format("http://%s:%s", InetAddress.getLocalHost().getHostAddress().toString(), port), new WindowListener() {

				@Override
				public void windowOpened(WindowEvent e) {
					// 开启一个web服务，用来下载
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								fileServer = new FileServer();
								fileServer.run(port, fileName);
							} catch (Exception e1) {
								LOGGER.error(e1);
								System.exit(1);
							}
						}
					}).start();
				}

				@Override
				public void windowIconified(WindowEvent e) {

				}

				@Override
				public void windowDeiconified(WindowEvent e) {

				}

				@Override
				public void windowDeactivated(WindowEvent e) {

				}

				@Override
				public void windowClosing(WindowEvent e) {
					fileServer.close();
				}

				@Override
				public void windowClosed(WindowEvent e) {
					fileServer.close();
				}

				@Override
				public void windowActivated(WindowEvent e) {
				}
			}).go();
		} catch (Exception e) {
			LOGGER.error(e);
			System.exit(1);
		}
	}
}
